package com.weishi.project.training.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.dto.DynamometerRankingDTO;
import com.weishi.project.api.vo.DynamometerRankingListVO;
import com.weishi.project.api.vo.HandUpCgyBean;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.mapper.DynamometerMapper;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 测功仪数据Service业务层处理
 */
@Service
public class DynamometerServiceImpl extends ServiceImpl<DynamometerMapper, Dynamometer> implements IDynamometerService {


    @Autowired
    private DynamometerMapper dynamometerMapper;

    /**
     * 测功仪成绩排名 接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    /**
     * 运动员接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 训练成绩 接口
     */
    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    /**
     * 测功仪分段 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;



    /**
     * 查询测功仪数据列表
     */
    @Override
    public List<Dynamometer> selectDynamometerList(Dynamometer dynamometer) {
        return dynamometerMapper.selectDynamometerList(dynamometer);
    }


    /**
     * 查询测功仪平均心率
     */
    @Override
    public Integer getAverageHeartRate(Integer userId, Integer trainingDayId, Integer trainingMode, Integer groupId) {
        return dynamometerMapper.getAverageHeartRate(userId , trainingDayId , trainingMode , groupId);
    }


    /**
     * 教练员端 -- 查询测功仪男女最新排名
     */
    @Override
    public AjaxResult getDynamometerRanking(DynamometerRankingDTO dynamometerRankingDTO) {
        DynamometerRankingListVO dynamometerRankingListVO = new DynamometerRankingListVO();

        //判断时间还是公里数 0 是公里数 1 是时间
        if(dynamometerRankingDTO.getTrainingMode() == 0){
            // 男性排名成绩
            List<DynamometerRanking> dynamometerList = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId()).eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex , 0).orderByAsc(DynamometerRanking::getLengthTime));
            dynamometerRankingListVO.setRankingMale(dynamometerList);

            // 女性排名成绩
            List<DynamometerRanking> dynamometerList2 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId()).eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex , 1).orderByAsc(DynamometerRanking::getLengthTime));
            dynamometerRankingListVO.setRankingFemale(dynamometerList2);
            return AjaxResult.success(dynamometerRankingListVO);
        }else{
            // 男性排名成绩
            List<DynamometerRanking> dynamometerList = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId()).eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex , 0).orderByDesc(DynamometerRanking::getMileage));
            dynamometerRankingListVO.setRankingMale(dynamometerList);

            // 女性排名成绩
            List<DynamometerRanking> dynamometerList2 = dynamometerRankingService.list(Wrappers.<DynamometerRanking>lambdaQuery().eq(DynamometerRanking::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId()).eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId()).eq(DynamometerRanking::getSex , 1).orderByDesc(DynamometerRanking::getMileage));
            dynamometerRankingListVO.setRankingFemale(dynamometerList2);
            System.out.println();
            return AjaxResult.success(dynamometerRankingListVO);
        }
    }


    /**
     * 教练员端 -- 手动新增运动员成绩
     */
    @Override
    public AjaxResult addDynamometer(JSONObject jsonObject) {
        com.alibaba.fastjson.JSONArray jsonArray = jsonObject.getJSONArray("list");
        List<HandUpCgyBean> dynamometerList = JSON.parseArray(jsonArray.toString(), HandUpCgyBean.class);
        for (int i = 0; i<dynamometerList.size(); i++){
            if(jsonObject.get("trainingMode").equals(0)){
                if(i == 0){
                    Dynamometer dynamometer = new Dynamometer();
                    StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                    dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                    dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                    dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                    dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                    dynamometer.setPower(jsonObject.get("totalpower").toString());
                    dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                    dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                    dynamometer.setCtime(new Date());
                    save(dynamometer);
                }else{
                    // 计算时间
                    if(i <= dynamometerList.size()){
                        int goUp = StringUtils.turnSecond(dynamometerList.get(i-1).getLengthTime());
                        int under = StringUtils.turnSecond(dynamometerList.get(i).getLengthTime());
                        Integer totals = goUp+under;

                        Dynamometer dynamometer = new Dynamometer();
                        StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                        dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                        dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                        dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                        dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                        dynamometer.setLengthTime(StringUtils.millisecondRotationTime(totals));
                        dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                        dynamometer.setPower(jsonObject.get("totalpower").toString());
                        dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                        dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                        dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                        dynamometer.setCtime(new Date());
                        save(dynamometer);
                    }
                }
            }else{
                // 计算公里数
                if(i == 0){
                    Dynamometer dynamometer = new Dynamometer();
                    System.out.println();
                    StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                    dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                    dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                    dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                    dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                    dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                    dynamometer.setPower(jsonObject.get("totalpower").toString());
                    dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                    dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                    dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                    dynamometer.setCtime(new Date());
                    save(dynamometer);
                }else{
                    if(i <= dynamometerList.size()){
                        double goUp = dynamometerList.get(i-1).getMileage();
                        double under = dynamometerList.get(i).getMileage();
                        double total = under + goUp;
                        Dynamometer dynamometer = new Dynamometer();
                        StringUtils.copyProperties(dynamometerList.get(i) , dynamometer);
                        dynamometer.setMileage(total);
                        dynamometer.setCtime(new Date());
                        dynamometer.setTrainingMode(Integer.parseInt(jsonObject.get("trainingMode").toString()));
                        dynamometer.setSportsmanId(Integer.parseInt(jsonObject.get("sportsmanId").toString()));
                        dynamometer.setSportsmanName(jsonObject.get("sportsmanName").toString());
                        dynamometer.setLengthTime(dynamometerList.get(i).getLengthTime());
                        dynamometer.setPulpNumber(Integer.parseInt(jsonObject.get("totalpulp").toString()));
                        dynamometer.setPower(jsonObject.get("totalpower").toString());
                        dynamometer.setTrainingDayId(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
                        dynamometer.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
                        dynamometer.setSex(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId , Integer.parseInt(jsonObject.get("sportsmanId").toString()))).getSex());
                        save(dynamometer);
                    }

                }

            }
        }

        // 新增教练员端的成绩
        TrainingGroupChannel trainingGroupChannel = new TrainingGroupChannel();
        trainingGroupChannel.setPower(jsonObject.get("totalpower").toString());
        if(Integer.parseInt(jsonObject.get("trainingMode").toString()) == 0){
            trainingGroupChannel.setAchievement(jsonObject.get("totalLength").toString());
        }else{
            trainingGroupChannel.setAchievement(jsonObject.get("totalResult").toString());
        }
        trainingGroupChannel.setGroupId(Integer.parseInt(jsonObject.get("groupId").toString()));
        trainingGroupChannelService.save(trainingGroupChannel);


        /**
         * 新增运动员测功仪数据
         * 0 加时间
         * 1 加距离
         */
        if(jsonObject.get("trainingMode").equals(0)){
            // 0 加时间
            // 新增运动员测功仪数据
            Integer totals = 0;
            for(int i = 0; i<dynamometerList.size(); i++){
                Integer under = StringUtils.turnSecond(dynamometerList.get(i).getLengthTime());
                totals += under;
            }
            System.out.println();
            DynamometerRanking dynamometerRanking = new DynamometerRanking();
            StringUtils.copyProperties(dynamometerList.get(dynamometerList.size()-1), dynamometerRanking);
            dynamometerRanking.setCtime(new Date());
            dynamometerRanking.setSportsmanId(Long.parseLong(jsonObject.get("sportsmanId").toString()));
            dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getSex().toString()));
            dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getName());
            dynamometerRanking.setGroupId(Long.parseLong(jsonObject.get("groupId").toString()));
            dynamometerRanking.setTrainingDayId(Long.parseLong(jsonObject.get("trainingDayId").toString()));
            dynamometerRanking.setLengthTime(StringUtils.millisecondRotationTime(totals));
            dynamometerRankingService.save(dynamometerRanking);

        }else{
            // 1 加距离
            // 新增运动员测功仪数据
            double totals = 0;
            for(int i = 0; i<dynamometerList.size(); i++){
                double under = dynamometerList.get(i).getMileage();
                totals += under;
            }
            DynamometerRanking dynamometerRanking = new DynamometerRanking();
            StringUtils.copyProperties(dynamometerList.get(dynamometerList.size()-1), dynamometerRanking);
            dynamometerRanking.setCtime(new Date());
            dynamometerRanking.setSportsmanId(Long.parseLong(jsonObject.get("sportsmanId").toString()));
            dynamometerRanking.setSex(Long.parseLong(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getSex().toString()));
            dynamometerRanking.setSportsmanName(sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getId, Long.parseLong(jsonObject.get("sportsmanId").toString()))).getName());
            dynamometerRanking.setGroupId(Long.parseLong(jsonObject.get("groupId").toString()));
            dynamometerRanking.setTrainingDayId(Long.parseLong(jsonObject.get("trainingDayId").toString()));
            dynamometerRanking.setMileage(totals);
            dynamometerRankingService.save(dynamometerRanking);
        }


        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 查询运动员测功仪实时数据
     */
    @Override
    public AjaxResult getRealTimeData(DynamometerRankingDTO dynamometerRankingDTO) {
        List<Dynamometer> list = list(Wrappers.<Dynamometer>lambdaQuery()
                .eq(Dynamometer::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId())
                .eq(Dynamometer::getGroupId , dynamometerRankingDTO.getGroupId())
                .eq(Dynamometer::getSportsmanId , dynamometerRankingDTO.getSportsmanId()));

        Integer index;
        List<Dynamometer> list2 = new ArrayList<>();
        // 判断 list 数量 大于 1000 每 20 条 取一条 小于 1000 或 大于 500 每10 个 取一个
        // 大于 200 小于 500  每 6 条 取一条 ，小于 200 大于 100 每 4 个取一个 小于 200 每 2个 取一个
        if(list.size() > 1000){
            index = 20;
                for (int i = 0; i<list.size(); i++){
                    index+=20;
                    if(index < list.size()){
                    list2.add(list.get(index));
                    }
            }
            return AjaxResult.success(list2);

        }else if(list.size() < 1000 && list.size() >500){
            index = 10;

                for (int i = 0; i<list.size(); i++){
                    index+=10;
                    if(index < list.size()){
                    list2.add(list.get(index));
                    }
                }
                return AjaxResult.success(list2);

        }else if(list.size() < 500 && list.size() >200){
            index = 6;

                for (int i = 0; i<list.size(); i++){
                    index+=6;
                    if(index < list.size()){
                    list2.add(list.get(index));
                    }
                }
                return AjaxResult.success(list2);

        }else if(list.size() < 200 && list.size() >100){
            index = 4;

                for (int i = 0; i<list.size(); i++){
                    index+=4;
                    if(index < list.size()){
                    list2.add(list.get(index));
                    }
                }
                return AjaxResult.success(list2);

        }else if(list.size() < 200){
            index = 2;

                for (int i = 0; i<list.size(); i++){
                    index+=2;
                    if(index < list.size()){
                    list2.add(list.get(index));
                    }
                }
                return AjaxResult.success(list2);
        }
        return AjaxResult.success();
    }


    /**
     * 教练员端 -- 查询运动员测功仪最新一条数据 ，加平均心率和最大心率
     */
    @Override
    public AjaxResult getLatest(DynamometerRankingDTO dynamometerRankingDTO) {
        List<Dynamometer> list = list(Wrappers.<Dynamometer>lambdaQuery()
                .eq(Dynamometer::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId())
                .eq(Dynamometer::getGroupId , dynamometerRankingDTO.getGroupId())
                .eq(Dynamometer::getSportsmanId , dynamometerRankingDTO.getSportsmanId())
                .orderByDesc(Dynamometer::getCtime));

        // 查询所有心率
        List<Dynamometer> maxHeartRateList = list(Wrappers.<Dynamometer>lambdaQuery()
                .eq(Dynamometer::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId())
                .eq(Dynamometer::getGroupId , dynamometerRankingDTO.getGroupId())
                .eq(Dynamometer::getSportsmanId , dynamometerRankingDTO.getSportsmanId())
                .orderByDesc(Dynamometer::getHeartRate));

        // 最大心率
        Integer maxHeartRate = 0;
        if(maxHeartRateList.size() > 0){
            // 取出最大心率
            maxHeartRate = maxHeartRateList.get(0).getHeartRate();
        }


        if(maxHeartRateList.size() > 0){
            for (int i = 0; i < maxHeartRateList.size(); i++){

            }
        }


        // 查询测功仪分段表的数据
        List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                        .eq(DynamometerSubsection::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId())
                        .eq(DynamometerSubsection::getGroupId , dynamometerRankingDTO.getGroupId())
                        .eq(DynamometerSubsection::getSportsmanId , dynamometerRankingDTO.getSportsmanId()));


        Double averageSpeeds = 0.0;
        Integer averageHeartRates = 0;
        Integer averagePropellerFrequencys = 0;
        if(dynamometerSubsectionList.size() > 0){
            // 平均速度
            Double averageSpeed = 0.0;
            // 平均心率
            Integer averageHeartRate = 0;
            // 平均浆频
            Integer averagePropellerFrequency = 0;

            for (int i = 0; i<dynamometerSubsectionList.size(); i++){
                averageSpeed+=dynamometerSubsectionList.get(i).getSpeed();
                averageHeartRate+=dynamometerSubsectionList.get(i).getHeartRate();
                averagePropellerFrequency+=Integer.parseInt(dynamometerSubsectionList.get(i).getPropellerFrequency());
            }
            averageSpeeds = averageSpeed/dynamometerSubsectionList.size();
            // 计算的平均心率结果
            averageHeartRates = averageHeartRate/dynamometerSubsectionList.size();
            averagePropellerFrequencys = averagePropellerFrequency/dynamometerSubsectionList.size();
        }




        // 判断是否有值
        if(list.size() == 0){
            return AjaxResult.success();
        }else{

            // 查询运动员成绩信息
            DynamometerRanking dynamometerRanking = dynamometerRankingService
                    .getOne(Wrappers.<DynamometerRanking>lambdaQuery()
                            .eq(DynamometerRanking::getTrainingDayId , dynamometerRankingDTO.getTrainingDayId())
                            .eq(DynamometerRanking::getGroupId , dynamometerRankingDTO.getGroupId())
                            .eq(DynamometerRanking::getSportsmanId , dynamometerRankingDTO.getSportsmanId()));

            if(StringUtils.isNotNull(dynamometerRanking)){
                // 返回数据
                Dynamometer dynamometer = new Dynamometer();
                StringUtils.copyProperties(dynamometerRanking , dynamometer);
                dynamometer.setPropellerFrequency(dynamometerRanking.getPropellerFrequency());
                dynamometer.setAverageHeartRate(averageHeartRates); // 平均心率
                dynamometer.setMaxHeartRate(maxHeartRate); // 最大心率
                dynamometer.setAveragePropellerFrequency(averagePropellerFrequencys.toString()); // 平均浆频
                dynamometer.setAveragePower(dynamometerRanking.getPower()); // 平均功率
                dynamometer.setAverageWatt(dynamometerRanking.getWatt()); // 平均瓦特
                dynamometer.setAverageSpeed(averageSpeeds); // 平均速度
                dynamometer.setAveragePeakForce(dynamometerRanking.getPeakForce()!=null ? dynamometerRanking.getPeakForce().doubleValue():0.0);  //平均峰力
                dynamometer.setAverageForces(dynamometerRanking.getAverageForce()!=null ? dynamometerRanking.getAverageForce().doubleValue() : 0.0); // 平均均力
                return AjaxResult.success(Optional.ofNullable(dynamometer));
            }

        }
        return null;
    }












}